package comcksys.authserver.config;

import comcksys.authserver.service.impl.RandomValueAuthorizationCodeServicesImpl;
import comcksys.authserver.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 配置授权服务器
 * EnableAuthorizationServer 开启授权服务器的自动化配置
 *
 * @author: yxzhang23
 * @time: 2021/4/8
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    /**
     * token存储路径
     */
    private final TokenStore tokenStore;

    private final ClientDetailsService clientDetailsService;

    private final PasswordEncoder passwordEncoder;

    /**
     * Redis操作工具类
     */
    private final RedisUtil redisUtil;

    @Autowired
    public AuthorizationServer(TokenStore tokenStore, ClientDetailsService clientDetailsService,
                               PasswordEncoder passwordEncoder, RedisUtil redisUtil) {
        this.tokenStore = tokenStore;
        this.clientDetailsService = clientDetailsService;
        this.passwordEncoder = passwordEncoder;
        this.redisUtil = redisUtil;
    }

    /**
     * 配置Token的基本信息
     * 是否支持刷新, Token存储位置, 有效期, 刷新Token有效期
     */
    @Bean
    AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setClientDetailsService(clientDetailsService);
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 2);
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 3);
        return tokenServices;
    }

    /**
     * 配制授权码的存储
     */
    @Bean
    AuthorizationCodeServices authorizationCodeServices() {
        return new RandomValueAuthorizationCodeServicesImpl(redisUtil);
    }

    /**
     * 配置令牌端点的安全约束（即设置该端点谁能访问）
     * checkTokenAccess是指一个Token校验的断电，可以直接访问
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    /**
     * TODO: 将客户端信息保存到数据库，通过CRUD接口可以进行操作
     * 配置客户端的详细信息
     * 配置客户端的id, secret, 资源id, 授权类型, 授权范围, 重定向uri
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("auth-client")
                .secret(passwordEncoder.encode("123"))
                .resourceIds("res1")
                .authorizedGrantTypes("authorization_code", "refresh_token")
                .scopes("all")
                .redirectUris("http://localhost:8082/index");
    }

    /**
     * 配置令牌的访问端点和令牌服务
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authorizationCodeServices(authorizationCodeServices())
                .tokenServices(tokenServices());
    }
}
